import { TranslationCard } from './components/TranslationCard';
import { FloatingToolbar } from './components/FloatingToolbar';
import { TranslationService } from './services/translationService';
import { domUtils } from './utils/domUtils';
import { LogService } from './services/logService';
import { handleError } from './utils/errorUtils';
import { AIService } from './services/aiService';

class ContentScript {
    constructor() {
        this.logger = new LogService('ContentScript');
        this.translationCard = new TranslationCard();
        this.floatingToolbar = new FloatingToolbar();
        this.translationService = new TranslationService();
        this.aiService = new AIService();
        
        this.lastSelectionTime = 0;
        this.SELECTION_DELAY = 300;
        
        this.setupEventListeners();
        this.logger.info("NODE_ENV", process.env.NODE_ENV);
        this.logger.debug("NODE_ENV", process.env.NODE_ENV);
        this.logger.info('Content script initialized');

        // 创建防抖后的处理函数
        this.debouncedHandleSelection = this.debounce(this.processSelection.bind(this), this.SELECTION_DELAY);
    }

    setupEventListeners() {
        try {
            document.addEventListener('mouseup', this.handleSelection.bind(this));
            document.addEventListener('click', this.handleClickOutside.bind(this));
            document.addEventListener('scroll', this.cleanup.bind(this));
            window.addEventListener('resize', this.cleanup.bind(this));

            this.floatingToolbar.on('translate', this.handleTranslate.bind(this));
            this.floatingToolbar.on('summarize', this.handleSummarize.bind(this));
            this.floatingToolbar.on('explain', this.handleExplain.bind(this));
            this.logger.debug('Event listeners setup completed');
        } catch (error) {
            this.logger.error(error, 'Failed to setup event listeners');
        }
    }

    async handleTranslate(text) {
        
        try {
            this.logger.debug('开始处理翻译请求', { text });
            const translation = await this.handleTranslation(text);
            this.logger.info('翻译成功', { translation });
            
            this.logger.debug('显示翻译结果', { translation });
            this.translationCard.show(translation, domUtils.getSelectionPosition());
            this.logger.info('Translation displayed successfully');
        } catch (error) {
            this.logger.error('contentscript error', error);
            const handledError = handleError(error, this.logger);
            this.translationCard.show(
                handledError.message, 
                domUtils.getSelectionPosition(), 
                true
            );
        }
    }

    async handleSummarize(text) {
        this.logger.debug('Summarization requested', { text });
        
        try {
            const summary = await chrome.runtime.sendMessage({
                action: "summarize",
                text: text
            });
            // const summary = await this.aiService.summarize(text);
            this.translationCard.show(
                summary, 
                domUtils.getSelectionPosition()
            );
            this.logger.info('Summary displayed successfully');
        } catch (error) {
            this.logger.error('contentscript error', error);
            const handledError = handleError(error, this.logger);
            this.translationCard.show(
                handledError.message, 
                domUtils.getSelectionPosition(), 
                true
            );
        }
    }

    async handleExplain(text) {
        this.logger.debug('Explanation requested', { text });
        
        try {
            const explanation = await chrome.runtime.sendMessage({
                action: "explain",
                text: text
            });
            this.translationCard.show(
                explanation, 
                domUtils.getSelectionPosition()
            );
            this.logger.info('Explanation displayed successfully');
        } catch (error) {
            const handledError = handleError(error, this.logger);
            this.translationCard.show(
                handledError.message,
                domUtils.getSelectionPosition(),
                true
            );
        }
    }

    // 添加防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 将原来handleSelection的核心逻辑移到这个方法
    processSelection() {
        try {
            const selectedText = domUtils.getSelectedText();
            if (selectedText) {
                const selectionRect = domUtils.getSelectionPosition();
                const position = domUtils.calculateToolbarPosition(selectionRect);
                this.floatingToolbar.show(position, selectedText);
                this.logger.debug('Selection toolbar shown', { 
                    text: selectedText,
                    position 
                });
            }
        } catch (error) {
            this.logger.error(error, 'Failed to handle text selection');
        }
    }

    // 简化后的handleSelection
    handleSelection(event) {
        this.debouncedHandleSelection();
    }

    handleClickOutside(event) {
        if (this.floatingToolbar.toolbar && 
            !this.floatingToolbar.toolbar.contains(event.target)) {
            setTimeout(() => {
                this.logger.debug('handleClickOutside', { event });
                if (!domUtils.getSelectedText()) {
                    this.floatingToolbar.remove();
                    this.translationCard.remove();
                }
            }, 1000);
        }
    }

    cleanup() {
        if (this.selectionTimeout) {
            clearTimeout(this.selectionTimeout);
        }
        this.floatingToolbar.remove();
        this.translationCard.remove();
    }

    async handleTranslation(text) {
        try {
            this.logger.debug('发送翻译请求', { text });
            const response = await chrome.runtime.sendMessage({
                action: "translate",
                text: text
            });

            this.logger.info('收到翻译响应', { response });
            if (response.error) {
                throw new Error(response.error);
            }
            
            return response.translation;
        } catch (error) {
            this.logger.error(error, '翻译失败');
            throw error;
        }
    }
}

// 初始化内容脚本
new ContentScript(); 